package org.compiere.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

import extend.org.compiere.utils.Util;

public class Mhrmsheduleemployee extends X_hrm_sheduleemployee {
	


	/**
	 * 
	 */
	private static final long serialVersionUID = -6297742032408929819L;
	

	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (Mhrmsheduleemployee.class);

	public Mhrmsheduleemployee(Properties ctx, int hrm_sheduleemployee_ID,
			String trxName) {
		super(ctx, hrm_sheduleemployee_ID, trxName);
	}

	public Mhrmsheduleemployee(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}
	
	private void updPeriod(PO po){
		// Upd period StartDate <-> EndDate
		Util.updPeriod(po, "C_BPartner_ID");
	}
	
	@Override
	public boolean save() {
		
		super.save();
		updPeriod(this);
		
		return true;
	}
	
	@Override
	public boolean delete(boolean force) {
		
		boolean de = super.delete(force);
		// copy Values
		updPeriod(new X_hrm_sheduleemployee(this.getCtx(), get_ID(), this.get_TrxName()));
		
		return de;
	}
	
	public static int getSheduleRule(int C_BPartner_ID, Timestamp dt){
		
		if(C_BPartner_ID == 0)
    		return 0;
				
		int result = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// Employee data from the card
		String sql_ = "SELECT HRM_SHEDULERULE_ID FROM ADEMPIERE.HRM_SHEDULEEMPLOYEE \n " +
						 "WHERE AD_CLIENT_ID="  + Env.getAD_Client_ID(Env.getCtx()) + " \n" +
						   "AND C_BPARTNER_ID=" + C_BPartner_ID + " \n" +
						   "AND " + DB.TO_DATE(dt) + " BETWEEN STARTDATE AND ENDDATE ";
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			rs = pstmt.executeQuery();
			if(rs.next())
				return rs.getInt(1);		
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}

		return result;
	}

public static int getSheduleRule_v(int C_BPartner_ID, Timestamp dt){
	
	if(C_BPartner_ID == 0)
		return 0;
			
	int result = 0;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	// Employee data from the card
	String sql_ = "SELECT SHEDULERULE_ID FROM HRM_SCHEDULESETTINGS_V \n " +
					 "WHERE AD_CLIENT_ID="  + Env.getAD_Client_ID(Env.getCtx()) + " \n" +
					   "AND C_BPARTNER_ID=" + C_BPartner_ID + " \n" +
					   "AND DATEFROM=" + DB.TO_DATE(dt) + " \n";
	try
	{
		pstmt = DB.prepareStatement(sql_,null);
		rs = pstmt.executeQuery();
		if(rs.next())
			return rs.getInt(1);		
	}
	catch (SQLException e)
	{
		s_log.log(Level.SEVERE, "product", e);
	}
	finally
	{
		DB.close(rs, pstmt);
		rs = null; pstmt = null;
	}

	return result;
 }

}
